package com.zzx.boot.serializable;

import com.google.gson.*;
import com.zzx.boot.emus.ChatTypes;
import com.zzx.boot.message.Message;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;

public class CustomSerializable implements JsonDeserializer<Message> {

    private static Gson gson = new Gson();

    @Override
    public Message deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        // 判断类型
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        // 获取类型
        String messageType = jsonObject.get("type").getAsString();
        ChatTypes chatTypes = ChatTypes.valueOf(messageType);
        return gson.fromJson(jsonElement, chatTypes.getMessage());
    }

    public static Gson gson() {
        return new GsonBuilder().serializeNulls().registerTypeAdapter(Message.class, new CustomSerializable()).create();
    }


}
